//
//  WBMainViewController.swift
//  weibo
//
//  Created by wenquan wang on 11/18/16.
//  Copyright © 2016 wenquan wang. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBMainViewController: UITabBarController {

    //timmer
    var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.setupChindControllers()
        setupComposeButton()
        
        //event
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
        setupTimmer()
        
        setupNewFeatureViews()
        
        //delegate
        delegate = self
        
        //notification
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private func userLogin(n: Notification){
        print("user login notification \(n)")
        var when = DispatchTime.now()
        if(n.object != nil)
        {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "user login is expired, please relogin!")
            
            when = DispatchTime.now()+2
        }
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            let vc = WBOAuthViewController()
            let nav = UINavigationController(rootViewController: vc)
            self.present(nav, animated: true, completion: nil)
        }
        
        
    }
    
    private var _orientations = UIInterfaceOrientationMask.portrait
    override var supportedInterfaceOrientations : UIInterfaceOrientationMask{
        get {return self._orientations}
        set {self._orientations = newValue}
    }
    
    // MARK: EVENT
    @objc private func composeStatus(){
        print("to do ......")
        //test interfaceOrientations
        // FIXME: 0 check login status
        
        let v = WBComposeTypeView.composeTypeView()
        
        v.show { [weak v](clsName) in
            print(clsName)
            guard let clsName = clsName,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type
            else {
                v?.removeFromSuperview()
                return
            }
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            
            self.present(nav, animated: true){
                v?.removeFromSuperview()
            }
        }
    }
    
    // MARK: controllers
    public lazy var composeButton:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}

extension WBMainViewController: UITabBarControllerDelegate{
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("will go to \(viewController)")
        
        let idx = (childViewControllers as NSArray).index(of: viewController)
        
        if selectedIndex == 0 && idx == selectedIndex{
            print ("click home tabbar!")
            
            let nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            
            vc.tableView?.setContentOffset(CGPoint(x:0, y: -64), animated: true)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                vc.loadData()
            })
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        return !viewController.isMember(of: UIViewController.self)
    }
}

extension WBMainViewController {
    func setupTimmer(){
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
    }
    @objc private func updateTimer(){
        if !WBNetworkManager.shared.userLogin {
            return
        }
        WBNetworkManager.shared.unreadCount{
            (count) in
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
        }
        print("timer is run...")
    }
}
//UI
extension WBMainViewController{
    
    public func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count
        composeButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
    }
    public func setupChindControllers(){
        /**
        //get sandbox json file
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil{
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        //load data from bundle
        do {
            let array1 = try JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
        }
        catch {
            objc_exception_rethrow()
        }
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]] else{
            return
        }
        */
        // 0. 获取沙盒 json 路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载 data
        var data = NSData(contentsOfFile: jsonPath)
        
        // 判断 data 是否有内容，如果没有，说明本地沙盒没有文件
        if data == nil {
            // 从 Bundle 加载 data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            
            data = NSData(contentsOfFile: path!)
        }
        
        // data 一定会有一个内容，反序列化
        // 反序列化转换成数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
            else {
                return
        }

        /**
        let array:[[String: AnyObject]] = [
            ["clsName": "WBHomeViewController" as AnyObject, "title":"Home" as AnyObject, "imageName":"home" as AnyObject,
             "visitorInfo": ["imageName":"", "message": "hello Home!"] as AnyObject],
         
            ["clsName": "WBMessageViewController" as AnyObject, "title":"Msg" as AnyObject, "imageName":"message_center" as AnyObject,
             "visitorInfo": ["imageName":"visitordiscover_image_message", "message": "hello Message!"] as AnyObject],
            
            ["clsName":"UIViewController" as AnyObject],
            
            ["clsName": "WBDiscoverViewController" as AnyObject, "title":"Disc" as AnyObject, "imageName":"discover" as AnyObject,
             "visitorInfo": ["imageName":"visitordiscover_image_message", "message": "hello Discover!"] as AnyObject],
            
            ["clsName": "WBProfileViewController" as AnyObject, "title":"Prof" as AnyObject, "imageName":"profile" as AnyObject,
             "visitorInfo": ["imageName":"visitordiscover_image_profile", "message": "hello Profile!"] as AnyObject],
        ]
        */
        //(array as NSArray).write(toFile: "/Users/wenquanwang/Desktop/demo.plist", atomically: true)
        
        
        // array to json
        //let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        //let fileURL = NSURL.fileURL(withPath: "/Users/wenquanwang/Desktop/demo.json")
        //data?.write(to: fileURL)
        //(data as NSData).write(toFile: "/Users/wenquanwang/Desktop/demo.json", atomically: true)
        var arrayM = [UIViewController]()
        for dict in array!{
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
    }
    ///create a view controller by dict
    ///dict: [clsName, title, imageName]
    private func controller(dict:[String:AnyObject])->UIViewController{
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "."+clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String: String]
            else{
                return UIViewController()
        }
        
        //clsName to cls
        let vc = cls.init()
        vc.visitorInfo = visitorDict
        
        vc.title = title
        //image
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName+"_selected")?.withRenderingMode(.alwaysOriginal)
        //set tabbar item title fond
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        //set font size
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14)], for: UIControlState(rawValue: 0))
        
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
}

extension WBMainViewController{
    func setupNewFeatureViews(){
        //0 check is Login
        if !WBNetworkManager.shared.userLogin
        {
            return
        }
        //1 check version
        
        //2 isNewVersion
        let v = isNewVersion ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
        
        // add to view
        //v.frame = view.bounds
        
        view.addSubview(v)
    }
    
    private var isNewVersion: Bool{
        print(Bundle.main.infoDictionary)
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print(currentVersion)
        
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = try? String(contentsOfFile: path) ?? ""
        print(sandboxVersion)
        
        _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        //return currentVersion != sandboxVersion
        return currentVersion != sandboxVersion
    }
}
